<template>
  <!-- 要货表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="700px"
      draggable
      @close="closeDialog"
      :close-on-click-modal="false"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        v-loading="loading1"
        :rules="rules"
        label-width="90px"
        style="display: flex"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商编号">
              <el-input
                v-model="formData.partnerCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称">
              <el-input
                v-model="formData.partnerName"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <!-- 工厂号-->
          <el-col :span="12">
            <el-form-item label="物料编号">
              <el-input
                v-model="formData.materialCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称">
              <el-input
                v-model="formData.materialName"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="props.title == '反馈信息'">
            <el-form-item label="反馈日期">
              <el-input
                v-model="formData.feedbackDateShow"
                placeholder="请选择反馈日期"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item label="反馈日期">
              <el-input
                v-model="formData.demandDateShow"
                placeholder="请选择反馈日期"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="props.title == '反馈信息'">
            <el-form-item label="反馈数量" prop="feedbackTotal">
              <el-input
                v-model="formData.feedbackTotal"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item label="反馈总数量" prop="feedbackTotal">
              <el-input
                v-model="formData.confirmQuantity"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer" v-if="!loading1">
          <el-button
            v-if="props.demandStatus == 2"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <!--(props.title == '反馈信息' && props.hhStatus==null)||props.demandStatus == 2"  -->
          <el-button
            v-if="props.demandStatus == 2"
            type="danger"
            :loading="loadingReject"
            @click="reject(props.cellId)"
            >驳 回</el-button
          >
          <el-button
            v-if="props.demandStatus == 3 && props.title == '确认信息'"
            type="danger"
            :loading="loadingRevoke"
            @click="revoke(props.cellId)"
            >撤 销</el-button
          >
          <el-button
            v-if="props.demandStatus == 3 && props.title == '确认信息'"
            type="primary"
            :loading="loadingAllow"
            @click="allown(props.cellId)"
            >允许发货</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";

defineOptions({
  name: "SRMREQUIREGOODSADDDIALOG",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  cellId: {
    type: String,
    default: () => {
      return "";
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  begirate: {
    type: String,
    default: () => {
      return "";
    },
  },
  endDate: {
    type: String,
    default: () => {
      return "";
    },
  },
  demandStatus: {
    type: Number,
    default: () => {
      return 0;
    },
  },
  hhStatus: {
    type: String,
    default: () => {
      return "";
    },
  },
});
const disabled = ref(false);
const loading1 = ref(false);
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (props.cellId) {
      loading1.value = true;
      // getOkCellList(props.cellId);
      if (props.title == "反馈信息") {
        getCellList(props.cellId);
      } else {
        getOkCellList(props.cellId);
      }
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  partnerId: [{ required: true, message: "未选择供应商", trigger: "change" }],
  arriveDate: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  demandDate: [
    {
      required: true,
      message: "未选择要货日期",
      trigger: "change",
    },
  ],
  materialId: [{ required: true, message: "未选择物料", trigger: "blur" }],
  storageLocationName: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  planQuantity: [
    { required: true, message: "未输入要货数量", trigger: "change" },
  ],
  dischargeHatchId: [
    { required: true, message: "未选择卸货口", trigger: "change" },
  ],
  purchasePlanNumber: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  filename: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  dischargeHatchId: "",
  dischargeHatchCode: "",
  dischargeHatchName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  // 物料需求ID
  demandId: props.id,
  // 需求日期
  demandDate: "",
  // 需求数量
  demandQuantity: 0,
  // 需求日期（格式化）
  demandDateShow: "",
  // 计划id
  planId: "",
  // 反馈日期
  feedbackDate: "",
  // 反馈总数量
  feedbackTotal: "",
  // 反馈日期（格式化）
  feedbackDateShow: "",
  allowSend: "",
  details: [
    {
      confirmQuantity: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      deleted: "",
      demandId: "",
      feedbackDate: "",
      feedbackDateShow: "",
      feedbackTotal: "",
      id: "",
      ids: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      remarks: "",
      version: "",
    },
  ],
});

// 获取反馈信息
const getCellList = async (id) => {
  await request({
    url: `/mes/srmdemandfeedback/getInfo/${id}`,
    method: "get",
  }).then((res) => {
    Object.assign(formData, { ...res.data });
    loading1.value = false;
    console.log("反馈", formData);
  });
};
// 获取确认数量一行单元格信息
const getOkCellList = async (id) => {
  await request({
    url: `/mes/srmdemandschedule/getConfirmQuantityCellInfo/${id}`,
    method: "get",
  }).then((res) => {
    Object.assign(formData, { ...res.data });
    loading1.value = false;
  });
};
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.demandId = props.id;
  // 需求日期s
  formData.demandDate = "";
  // 需求数量
  formData.demandQuantity = 0;
  // 需求日期（格式化）
  formData.demandDateShow = "";
  // 计划id
  formData.planId = "";
  disabled.value = false;

  formData.feedbackDateShow = "";
  // 是否允许发货
  formData.allowSend = "";
}

const loading = ref(false);

// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  return !(
    time.getTime() <= dayjs(props.endDate) &&
    time.getTime() >= dayjs(props.begirate)
  );
};

/** 订货计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      formData.demandId = formData.demandId ? formData.demandId : props.id;
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/srmdemandschedule/confirm",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 驳回按钮
const loadingReject = ref(false);
async function reject(id: any) {
  ElMessageBox.confirm("确认驳回该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loadingReject.value = true;
    await request({
      url: `/mes/srmdemandschedule/reject/${id}`,
      method: "get",
    })
      .then((res) => {
        ElMessage.success("驳回成功！");
        closeDialog();
        emit("reset-table", formData.id);
      })
      .finally(() => {
        loadingReject.value = false;
      });
  });
}
// 撤销按钮
const loadingRevoke = ref(false);
async function revoke(id: any) {
  ElMessageBox.confirm("确认撤销该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loadingRevoke.value = true;
    await request({
      url: `/mes/srmdemandschedule/revoke/${id}`,
      method: "get",
    })
      .then((res) => {
        ElMessage.success("撤销成功！");
        closeDialog();
        emit("reset-table", formData.id);
      })
      .finally(() => {
        loadingRevoke.value = false;
      });
  });
}
// 允许发货按钮
const loadingAllow = ref(false);
async function allown(id: any) {
  ElMessageBox.confirm("确认允许发货吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loadingAllow.value = true;
    await request({
      url: `/mes/srmdemandfeedback/allowShipment/${id}`,
      method: "get",
    })
      .then((res) => {
        ElMessage.success("发货成功！");
        closeDialog();
        emit("reset-table", formData.id);
      })
      .finally(() => {
        loadingAllow.value = false;
      });
  });
}
onMounted(() => {});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>

<style lang="scss" scoped>
.formTable {
  :deep(.el-scrollbar__wrap) {
    max-height: 200px;
    overflow-y: auto;
  }
}
</style>
